/**
 * Created by xuxin on 16/3/22.
 */
import Vue from 'vue'
import ApiMap from 'ApiMap'
import Conf from 'config'
import axios from 'axios'
import qs from 'qs'
import config from 'config'
import message from 'message'
import { Tip }  from 'util'
import router from '../router'

// android 4.1不支持promise
//if (!window.Promise) {
let Promise = require('es6-promise').Promise
//}
//默认 Content-Type 是 ‘application/x-www-form-urlencoded’。
let defaultsHeader = {'Content-Type':'x-www-form-urlencoded'}
let stream = weex.requireModule('stream')
let Loading = {
  hide:function(){},
  show:function(){}
}
let localStorageCtrl={
  clearAll:function(){}
}
let xhh = {
  goAppLogin:function(){}
}

function noop () {}

function requireLogin (logined) {
  return !(parseInt(logined) !== 0)
}

function redirect () {
  //urlService.setRedirectUrl()
  ///urlService.go('login')
  router.push('/login')
}

function jsonToQueryString (json) {
  return '?' +
    Object.keys(json).map(function (key) {
      return encodeURIComponent(key) + '=' +
        encodeURIComponent(json[key])
    }).join('&')
}

function wrapFetchPromise(opt){
  return new Promise((resolve, reject)=>{
    stream.fetch(opt, (res)=>{
      if(res.ok){
        resolve(res)
      }else{
        reject(res)
      }
    })
  })
}
function request (options) {
  //通过key取url值，为空则返回

  let url = (config.localConf.proxyHost + '/' + ApiMap[options.key]) || null
  //let url = ('http://10.15.168.34:10086/upload.php') || null
  if (!url) return

  let resolve = options.resolve || noop
  let reject = options.reject || noop
  let method = options.method || 'get'
  let data = options.data || {}
  data.client = data.client || 'wap'

  let isHideTip = Conf.noTipAjax.indexOf(options.key) > -1
  let noDirect = Conf.apiNoDirect.indexOf(options.key) > -1
  let isHideLoading = Conf.apiNoDirect.indexOf(options.key) > -1
  // 用alert报错
  let alertErrorMsg = Conf.alertErrorMsg.indexOf(options.key) > -1

  if (!isHideLoading) {
    Loading.show()
  }

  let promise = null

  if (method === 'get') {
    url += jsonToQueryString(data)
    promise = wrapFetchPromise({method:'GET',type: 'json',url: url})
  } else {
    promise = wrapFetchPromise({method:'POST',type: 'json',url: url,body:qs.stringify(data)})
  }

  return promise
    .then(function (response) {
      let res = response.data
      if (res && res.boolen) {
        res.boolen = parseInt(res.boolen)   //字符串转数字
      }
      if (requireLogin(res.logined)) {      //需登录则跳到登陆页面
        //localStorageCtrl.clearAll()
        Conf.isLogin = false
        if (!noDirect) {
          redirect()
        }
      }
      
      if (res && !res.boolen && !isHideTip) { //没找到则需弹tip
        if (alertErrorMsg) {
          //wap.vm.$Alert(res.message)
        } else {
          Tip.show(res.message)
        }
      }

      if (!isHideLoading) {
        Loading.hide()
      }

      resolve(res)

      return new Promise(function (resolve, reject) {
        resolve(res)
      })
    }, function (response) {
      Tip.show(response.statusText || message.requestFail)
      //window.Vue.XUtils.closePop()
      if (!isHideLoading) {
        Loading.hide()
      }
      reject({
        response: response,
        api: url,
        time: (new Date()).getTime() / 1000
      })
      return new Promise(function (resolve, reject) {
        reject(response)
      })
    })
}

let api = {}

function createApi (key) {
  api[key] = function (options) {
    // 检测网络状态 安卓以外的 通过这种方式监测网络
    // 在weex里暂时无法实现
    // if ((typeof navigator.onLine === 'boolean' && !navigator.onLine)) {
    //   Tip.show(message.offline)
    //   //window.Vue.XUtils.closePop()
    //   options.reject || options.reject()
    //   return false
    // }
    options = options || {}
    options.key = key
    return request(options)
  }
}

for (let key in ApiMap) {
  if (ApiMap.hasOwnProperty(key)) {
    createApi(key)
  }
}

export default api
